package com.soonfor.evaluate.tools;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.widget.ImageView;
import android.widget.Toast;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.soonfor.evaluate.activity.CustomScanAct;
import com.squareup.picasso.Picasso;
import com.tbruyelle.rxpermissions2.Permission;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageUtils {
    public static void loadImage(Context context, String url, ImageView iv) {
        if(iv!=null) {
            Picasso.with(context).load(jointImageURL(url))
                    .placeholder(R.drawable.no_picture_icon)
                    .error(R.drawable.no_picture_icon)
                    .into(iv);
        }
    }
    public static void loadImage(Context context, String url, ImageView iv, int defaultId) {
        if(iv!=null) {
            Picasso.with(context).load(jointImageURL(url))
                    .placeholder(defaultId)
                    .error(defaultId)
                    .into(iv);
        }
    }
    public static void loadImage2(Context context, String url, ImageView iv) {
        if(iv!=null) {
            Picasso.with(context).load(jointImageURL(url))
                    .placeholder(R.drawable.no_picture_icon)
                    .error(R.drawable.no_picture_icon)
                    .into(iv);
        }
    }

    private static String jointImageURL(String url) {
        if (url.startsWith("http") || url.startsWith("https")) {
            return url;
        } else {
            return UserInfo.DOWNLOAD_FILE + "?filepath=" + url;
        }
    }

    /**
     * 扫描二维码
     */
    public static void sanBarCode(final Activity activity) {
        PermissionUtils.openToScan(activity, new PermissionUtils.OpenListener() {
            @Override
            public void open() {
                /**
                 * * 二维码扫描
                 */
                IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
                intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
                        .setPrompt("对齐QR码/条码框内进行扫描")//写那句提示的话
                        .setCameraId(0)
                        .setBeepEnabled(true)
                        .setBarcodeImageEnabled(true)
                        .setOrientationLocked(true)
                        .setCaptureActivity(CustomScanAct.class) // 设置自定义的activity是CustomActivity
                        .initiateScan(); // 初始化扫描
            }
        });

    }

    /**
     * 选择相册图片
     *
     * @param mActivity
     * @param maxNum 最大张数
     * @selectionMedia 已选图片
     */
    public static void choosePicture(final Activity mActivity, final int requestCode, final int maxNum, final List<LocalMedia> selectionMedia) {
        PermissionUtils.getInstance().requestPromisssions(mActivity, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        //启动相册并拍照
                        PictureSelector.create(mActivity)
                                .openGallery(PictureMimeType.ofImage())
                                .isCamera(true)
                                .imageSpanCount(3)
                                .maxSelectNum(maxNum)
                                .compress(true)
                                .selectionMedia(selectionMedia)
                                // .compressGrade(Luban.CUSTOM_GEAR)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     * @param videoPath 视频的路径
     * @param width 指定输出视频缩略图的宽度
     * @param height 指定输出视频缩略图的高度度
     * @param kind 参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *            其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     *
     @return 指定大小的视频缩略图
     */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height,
                                     int kind) {
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);

        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    /*
     * * 选择相册视频
     *
     * @param mActivity
     * @param maxNum 最大张数
     * @selectionMedia 已选视频
     * */
    public static void videoSelect(final Activity context, final int tiple, final int maxSelNum, final List<LocalMedia> lastMedias, final int requestCode){
        PermissionUtils.getInstance().requestPromisssions(context, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        //启动相册并拍照
                        PictureSelector.create(context)
                                .openGallery(PictureMimeType.ofVideo())
                                .isCamera(true)
                                .imageSpanCount(3)
                                .compress(true)
                                .maxSelectNum(maxSelNum)
                                .isCamera(false)
                                //.compressGrade(Luban.THIRD_GEAR)
                                .selectionMode(tiple)
                                .selectionMedia(lastMedias)
                                .forResult(requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

       /**
     * 选择相册图片
     *
     * @param context
     * @param maxSelNum
     */
    public static void pictureSelect(final Activity context, final int tiple, final int maxSelNum, final List<LocalMedia> lastMedias, final int requestCode) {
        PermissionUtils.getInstance().requestPromisssions(context, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        //启动相册并拍照
                        PictureSelector.create(context)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                                //.theme()//主题样式(不设置为默认样式) 也可参考 demo values/styles 下 例如：R.style.picture.white.style
                                .maxSelectNum(maxSelNum)// 最大图片选择数量 int
                                // .minSelectNum()// 最小选择数量 int
                                .imageSpanCount(3)// 每行显示个数 int
                                .selectionMode(maxSelNum > 1 ? PictureConfig.MULTIPLE : PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .previewImage(true)// 是否可预览图片 true or false
                                .previewVideo(false)// 是否可预览视频 true or false
                                .enablePreviewAudio(false) // 是否可播放音频 true or false
                                // .compressGrade(Luban.THIRD_GEAR)// luban 压缩档次，默认 3 档 Luban.THIRD_GEAR、Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                                .isCamera(true)// 是否显示拍照按钮 true or false
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认 true
                                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1 之间 如设置 .glideOverride()无效
                                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                                .enableCrop(false)// 是否裁剪 true or false
                                .compress(true)// 是否压缩 true or false
                                //.compressMode()//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                                //.glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                //.withAspectRatio()// int 裁剪比例 如 16:9 3:2 3:4 1:1 可自定义
                                .hideBottomControls(true)// 是否显示 uCrop 工具栏，默认不显示 true or false
                                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                                //.openClickSound(false)// 是否开启点击声音 true or false
                                .selectionMedia(lastMedias)// 是否传入已选图片 List<LocalMedia> list
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                .cropCompressQuality(90)// 裁剪压缩质量 默认 90 int
                                .forResult(requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    /**
     * 打开相机拍照
     * @param context
     */
    public static void picOpenCamera(final Activity context, final int requestCode) {
        PermissionUtils.getInstance().requestPromisssions(context, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        //启动相机并拍照
                        PictureSelector.create(context)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    /**
     * 打开相册选择照片
     * @param context
     */
    public static void picOpenGallery(final Activity context, final int tiple, final int maxSelNum, final List<LocalMedia> lastMedias, final int requestCode) {
        PermissionUtils.getInstance().requestPromisssions(context, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        //启动相册并拍照
                        PictureSelector.create(context)
                                .openGallery(PictureMimeType.ofImage())
                                .isCamera(false)
                                .imageSpanCount(3)
                                .compress(true)
                                .maxSelectNum(maxSelNum)
                                .isCamera(true)
                                //.compressGrade(Luban.THIRD_GEAR)
                                .selectionMode(tiple)
                                .selectionMedia(lastMedias)
                                .forResult(requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    /**
     * 选择图片或拍照后，获取选中图片的路径集合
     */
    public static ArrayList<String> getPicPaths(Intent data) {
        ArrayList<String> resultList = new ArrayList<>();
        if (data != null) {
            List<LocalMedia> medias = PictureSelector.obtainMultipleResult(data);
            if (medias != null && medias.size() > 0) {
                for (int i = 0; i < medias.size(); i++) {
                    resultList.add(medias.get(i).getCompressPath());
                }
            }
        }
        return resultList;
    }


    /**
     * 跳转至系统相册
     */
    public static void takePictureBySysAlbum(final Activity activity, final int requestCode) {
        PermissionUtils.getInstance().requestPromisssions(activity, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setType("image/*"); // 设置文件类型
                        intentFromGallery.setAction(Intent.ACTION_PICK);
                        activity.startActivityForResult(intentFromGallery, requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                        Toast.makeText(activity, "您关闭了读取权限，无法调取系统相册！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    /**
     * //调用系统相机
     *
     * @param activity    当前activity
     * @param file        拍照后照片存储路径
     * @param requestCode 调用系统相机请求码
     */
    public static void takePictureBySysCamera(final Activity activity, final File file, final int requestCode) {
        PermissionUtils.getInstance().requestPromisssions(activity, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        Intent intentCamera = new Intent();
                        try {
                            if (file.exists()) {
                                file.delete();
                            }
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Uri imageUri = Uri.fromFile(file);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//Android7.0以上
                            imageUri = FileProvider.getUriForFile(activity, "com.estronger.shopmanage.fileprovider", file);//通过FileProvider创建一个content类型的Uri
                            intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                        }
                        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        //将拍照结果保存至photo_file的Uri中，不保留在相册中
                        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        activity.startActivityForResult(intentCamera, requestCode);
                    }

                    @Override
                    public void denial(Permission permission) {
                       }

                    @Override
                    public void fail() {

                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

    /**
     * 获取解析后的条码内容
     */
    public static String getBarCodeContent(int requestCode, int resultCode, Intent data) {
        String finalResult = "";
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            ArrayList<String> pathList = ImageUtils.getPicPaths(data);
            if (pathList.size() > 0 && pathList.get(0) != null) {
                String picPath = pathList.get(0);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_4444;
                Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);
                // 在这里我用到的 getSmallerBitmap 非常重要，下面就要说到
                bitmap = getSmallerBitmap(bitmap);
                // 获取bitmap的宽高，像素矩阵
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                int[] pixels = new int[width * height];
                bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
                // 最新的库中，RGBLuminanceSource 的构造器参数不只是bitmap了
                RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
                BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
                Reader reader = new MultiFormatReader();
                Result result = null;
                // 尝试解析此bitmap，！！注意！！ 这个部分一定写到外层的try之中，因为只有在bitmap获取到之后才能解析。写外部可能会有异步的问题。（开始解析时bitmap为空）
                try {
                    result = reader.decode(binaryBitmap);
                    finalResult = result.toString().trim();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (ChecksumException e) {
                    e.printStackTrace();
                } catch (FormatException e) {
                    e.printStackTrace();
                }
            }
        } else {
            IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (intentResult != null) {
                if (intentResult.getContents() == null) {
                } else {
                    // scanResult 为获取到的字符串
                    String scanResult = intentResult.getContents();
                    finalResult = scanResult == null ? "" : scanResult.trim();
                }
            }
        }
        return finalResult;
    }

    public static Bitmap getSmallerBitmap(Bitmap bitmap) {
        int size = bitmap.getWidth() * bitmap.getHeight() / 160000;
        if (size <= 1) return bitmap; // 如果小于
        else {
            Matrix matrix = new Matrix();
            matrix.postScale((float) (1 / Math.sqrt(size)), (float) (1 / Math.sqrt(size)));
            Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            return resizeBitmap;
        }
    }
}
